package com.elite;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.holders.StringHolder;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.tempuri.WebServiceTest;
import org.tempuri.WmgwLocator;

import com.dbic.sendMessage.client.MtNewMessage;
import com.dbic.sendMessage.client.SmsNewOperatorService;
import com.dbic.sendMessage.client.SmsNewOperatorServiceLocator;
import com.dbic.sendMessage.client.SmsNewOperator_PortType;
import com.elitecrm.admin.UnicodeInputStream;
import com.elitecrm.admin.UnicodeReader;



public class KKSMS implements Runnable{
	private static final Log log=LogFactory.getLog(DBSMS.class);
	public static com.elite.FtpBean ftpbean;
	public static String times;
	private boolean flag = true; 
	private static int Hz =1; 
	private static String sql =" select * from Documentout where DOCTYPE=3 and ((Status=0) or (Status!=1 and TrialCount<TrialCountLimit)) and expectedstartdate<=getdate() "; 
	private static String update_sql="";
	public static String username;
	public static String username1;
	public static String password;
	public static String password1;
	public static String XHH;
	public static String XHH1;
	private static String LastTryDateTime="";
	private static String FinishDateTime="";
	public static String IP;
	private static int xh_int=0;
	private static SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
	
	public static String getIP() {
		return IP;
	} 
	public static void setIP(String ip) {
		IP = ip;
	}
	public static com.elite.FtpBean getFtpbean() {
		return ftpbean;
	}
	public static void setFtpbean(com.elite.FtpBean ftpbean) {
		KKSMS.ftpbean = ftpbean;
	}
	public static String getTimes() {
		return times;
	}
	public static void setTimes(String times) {
		KKSMS.times = times;
	}
	public static String getUsername() {
		return username;
	}
	public static void setUsername(String username) {
		KKSMS.username = username;
	}
	public static String getUsername1() {
		return username1;
	}
	public static void setUsername1(String username1) {
		KKSMS.username1 = username1;
	}
	public static String getPassword() {
		return password;
	}
	public static void setPassword(String password) {
		KKSMS.password = password;
	}
	public static String getPassword1() {
		return password1;
	}
	public static void setPassword1(String password1) {
		KKSMS.password1 = password1;
	}
	public static String getXHH() {
		return XHH;
	}
	public static void setXHH(String xhh) {
		XHH = xhh;
	}
	public static String getXHH1() {
		return XHH1;
	}
	public static void setXHH1(String xhh1) {
		XHH1 = xhh1;
	}
	public static String getdesc(String a){
    	if(a.equals("1111")){
    		return "未知异常";
    	}else if(a.equals("0001")){
    		return "发送失败";
    	}else if(a.equals("0002")){
    		return "帐号密码验证错误";
    	}else if(a.equals("0003")){
    		return "IP限制访问";
    	}else if(a.equals("0004")){
    		return "群发号码过多，超出100个";
    	}else if(a.equals("0005")){
    		return "内容含非法字";
    	}else if(a.equals("0006")){
    		return "不允许群发的时段";
    	}else{
    		return "未知错误:"+a;
    	}
    }
	public static Element ElementRoot(String xml) throws JDOMException, IOException {
		SAXBuilder saxBuilder=new SAXBuilder();
		StringReader stringIn=new StringReader(xml);
		Document document=saxBuilder.build(stringIn);
		return document.getRootElement();
	}
	public static String getElementValue(Element elmt) {
		return elmt==null?"":elmt.getValue();
	}
	public static final String bytesToHexString(byte[] bArray) { 
	    StringBuffer sb = new StringBuffer(bArray.length); 
	    String sTemp; 
	    for (int i = 0; i < bArray.length; i++) { 
	     sTemp = Integer.toHexString(0xFF & bArray[i]); 
	     if (sTemp.length() < 2) 
	      sb.append(0); 
	     sb.append(sTemp.toUpperCase()); 
	    } 
	    return sb.toString(); 
	}
	public static void main(String[] args) throws HttpException, IOException{
         String a="我们在一起";
         a=URLDecoder.decode(a,"UTF-8");
         System.out.println(a);

	}
	private String getxml(String phone,String content){
		String xml="<?xml version='1.0' encoding='utf-8'?>" +
				"<data><bid>"+username+"</bid>" +
				"<pwd>"+password+"</pwd>" +
				"<phonenumber>"+phone+"</phonenumber>" +
				"<sendcontent>"+content+"</sendcontent></data>";
		return xml;
	}
	  private static String getHexString(byte b) {   
	        String hexStr = Integer.toHexString(b);   
	        int m = hexStr.length();   
	        if (m < 2) {   
	            hexStr = "0" + hexStr;   
	        } else {   
	            hexStr = hexStr.substring(m - 2);   
	        }   
	        return hexStr;   
	    }   
	  
	    private static String getBinaryString(int i) {   
	        String binaryStr = Integer.toBinaryString(i);   
	        int length = binaryStr.length();   
	        for (int l = 0; l < 8 - length; l++) {   
	            binaryStr = "0" + binaryStr;   
	        }   
	        return binaryStr;   
	    }   
	public static String gbToUtf8(String str) throws UnsupportedEncodingException {   
        StringBuffer sb = new StringBuffer();   
        for (int i = 0; i < str.length(); i++) {   
            String s = str.substring(i, i + 1);   
            if (s.charAt(0) > 0x80) {   
                byte[] bytes = s.getBytes("Unicode");   
                String binaryStr = "";   
                for (int j = 2; j < bytes.length; j += 2) {   
                    // the first byte   
                    String hexStr = getHexString(bytes[j + 1]);   
                    String binStr = getBinaryString(Integer.valueOf(hexStr, 16));   
                    binaryStr += binStr;   
                    // the second byte   
                    hexStr = getHexString(bytes[j]);   
                    binStr = getBinaryString(Integer.valueOf(hexStr, 16));   
                    binaryStr += binStr;   
                }   
                // convert unicode to utf-8   
                String s1 = "1110" + binaryStr.substring(0, 4);   
                String s2 = "10" + binaryStr.substring(4, 10);   
                String s3 = "10" + binaryStr.substring(10, 16);   
                byte[] bs = new byte[3];   
                bs[0] = Integer.valueOf(s1, 2).byteValue();   
                bs[1] = Integer.valueOf(s2, 2).byteValue();   
                bs[2] = Integer.valueOf(s3, 2).byteValue();   
                String ss = new String(bs, "UTF-8");   
                sb.append(ss);   
            } else {   
                sb.append(s);   
            }   
        }   
        return sb.toString();   
    }   
	private String SendSMS(String phone,String content) {
		log.info("phone:"+phone);
		log.info("content:"+content);
		String reslutValue="";
		try{
//			 content=new String(content.getBytes(),"gb2312");
//			 log.info("content:"+content);
			 content=URLDecoder.decode(content,"UTF-8");
			 log.info("content:"+content);
			 String xml=getxml(phone,content);
			 log.info("xml_xml:"+xml);		
			 
             PostMethod post=new PostMethod(IP);
			 post.setRequestBody(xml);
			 post.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
			 HttpClient httpclient=new HttpClient();
			 int result_code=httpclient.executeMethod(post);
			 System.out.print("result_code:"+result_code);
		     UnicodeInputStream uin=new UnicodeInputStream(post.getResponseBodyAsStream(),"utf-8");
		     InputStreamReader in=new InputStreamReader(uin,uin.getEncoding());
		     BufferedReader rd=new BufferedReader(in);
		     reslutValue=rd.readLine(); 
		     rd.close();
			 post.releaseConnection();	
			 
//			 URL url=new URL(IP);
//			 HttpURLConnection conn=(HttpURLConnection)url.openConnection();
//			 conn.setRequestMethod("POST");
//			 conn.setUseCaches(false);
//			 conn.setInstanceFollowRedirects(true);
//			 conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
//			 conn.setConnectTimeout(60000);
//			 conn.setReadTimeout(60000);
//			 conn.setDoOutput(true);
//			 conn.connect();
//			 DataOutputStream out=new DataOutputStream(conn.getOutputStream()); 
//			 out.writeBytes(xml); 
//		     out.flush();
//		     out.close();
//		     UnicodeInputStream uin=new UnicodeInputStream(conn.getInputStream(),"utf-8");
//		     InputStreamReader in=new InputStreamReader(uin,uin.getEncoding());
//		     BufferedReader rd=new BufferedReader(in);
//		     reslutValue=rd.readLine(); 
//		     rd.close();
//		     conn.disconnect();	 
		}catch(Exception e){
			log.error("SendSMS_error:"+getERRO(e));
		}
		return reslutValue;
	}
	private String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw = new StringWriter();  
            e.printStackTrace(new PrintWriter(sw, true));  
            str = sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}
	public void run(){
		log.info("---------------------酷开短信接口----------------------------");
		log.info("IP:"+IP);
		log.info("用户username:"+username);
		log.info("用户password:"+password);
		password=DigestUtils.md5Hex(password);
		log.info("用户password加密后:"+password);
		while(flag){
			try{
				log.info("sss:"+times);
				Hz=Integer.parseInt(times);
			}catch(Exception e){
				log.info("错误:"+e);
				log.info("因为获取运行频率出错，改为默认频率1分钟运行");
			}
			log.info("扫描documentout表中未处理的记录："+sql);
			List list=null;
			try{
				list=ftpbean.chaxun(sql);
			}catch(Exception e){
				log.error("扫描documentout表_error:"+getERRO(e));
			}
			if(list!=null){
				for(int i=0;i<list.size();i++){
					Map map=(Map)list.get(i); 
					String mobile=Util.filterForObject(map.get("DocumentTo"));
					String DocumentPath=Util.filterForObject(map.get("DocumentPath"));
					String TrialCountLimit=Util.filterForObject(map.get("TrialCountLimit"));
					String DocumentOut_GUID=Util.filterForObject(map.get("DocumentOut_GUID"));
					if(1==1){
						if(1==1){
							Date d=new Date();
							LastTryDateTime=formatter.format(d);
							FinishDateTime=formatter.format(d);
                            String reslutValue=SendSMS(mobile,DocumentPath);
                            log.info("返回结果:"+reslutValue);
                            Element root;
                            String RESULT_CODE="";
                            String RESULT_MSG="";
							try {
								root=ElementRoot(reslutValue);
								RESULT_CODE=getElementValue(root.getChild("RESULT_CODE"));
								RESULT_MSG=getElementValue(root.getChild("RESULT_MSG"));
							}catch (Exception e) {
								log.error(getERRO(e));
							}
							if(reslutValue!=null&&reslutValue!=""){
								if("0000".equals(RESULT_CODE)){							
									update_sql=" update DocumentOut set Status=1,TrialCount=TrialCount+1,LastTryDateTime='"+LastTryDateTime+"',FinishDateTime='"+FinishDateTime+"',ModifiedDate=getdate() where DocumentOut_GUID='"+DocumentOut_GUID+"'";		
								}else{	
									if(RESULT_CODE!=null&&!RESULT_CODE.equals("")){
										update_sql=" update DocumentOut set FailCode="+RESULT_CODE+",FailDescription='"+RESULT_MSG+"',Status=5,TrialCount=TrialCount+1,LastTryDateTime='"+LastTryDateTime+"',FinishDateTime='"+FinishDateTime+"',ModifiedDate=getdate() where DocumentOut_GUID='"+DocumentOut_GUID+"'";			
										
									}else{
										update_sql=" update DocumentOut set FailDescription='"+RESULT_MSG+"',Status=5,TrialCount=TrialCount+1,LastTryDateTime='"+LastTryDateTime+"',FinishDateTime='"+FinishDateTime+"',ModifiedDate=getdate() where DocumentOut_GUID='"+DocumentOut_GUID+"'";			
										
									}
								}
								log.info("update_sql:"+update_sql);
								try{
									int a=ftpbean.update(update_sql);
									log.info("是否更新DocumentOut成功:"+a);
								}catch(Exception e){
									log.error(getERRO(e));
								}
								
							}else{
								log.info("DocumentOut查询无结果");
							}
						}		
					}
				}
				
			}else{
				log.info("没有需要发送的短信");
			}
                
			try{
				Thread.sleep(Hz*1000);
			}catch(Exception e){
				log.error("定时错误:"+getERRO(e));
			}
		}
	}

	

}





















